package pers.email;

import pers.email.config.EmailConfig;
import pers.email.exception.MyEmailException;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

public class Email {

    private EmailConfig mailConfig;

    public Email(EmailConfig mailConfig){
        this.mailConfig = mailConfig;
    }

    public Email() throws MyEmailException {
        mailConfig = new EmailConfig.Builder()
                .addHost("smtp.qq.com")
                .addPort("587")
                .addAuth(true)
                .addStarttls(true)
                .addMailUser("3200438004@qq.com")
                .addMailPassword("jdcnokvjqzuldgaa")
                .build();
    }

    /**
     * 发送电子邮件
     * @param email 电子邮件地址
     * @param subject 电子邮件标题
     * @param text 电子邮件内容
     * @param debug 是否启用debug模式
     */
    public void sendEmail(String email, String subject, String text, Boolean debug){
        Properties props = new Properties();
        props.put("mail.smtp.host", mailConfig.getHost());
        props.put("mail.smtp.port", mailConfig.getPort());
        props.put("mail.smtp.auth", String.valueOf(mailConfig.getAuth()));
        props.put("mail.smtp.starttls.enable",String.valueOf(mailConfig.getStarttls()));

        try {
            PopupAuthenticator auth = new PopupAuthenticator(mailConfig);
            Session session = Session.getInstance(props, auth);
            if(debug != null && debug) {
                session.setDebug(debug);//打印Debug信息
            }
            MimeMessage message = new MimeMessage(session);
            Address addressFrom = new InternetAddress(mailConfig.getMailUser(), "");//第一个参数为发送方电子邮箱地址；第二个参数为发送方邮箱地址的标签
            Address addressTo = new InternetAddress(email, "");//第一个参数为接收方电子邮箱地址；第二个参数为接收方邮箱地址的标签
            message.setSubject(subject);
            message.setText(text);
            message.setFrom(addressFrom);
            message.addRecipient(Message.RecipientType.TO, addressTo);
            message.saveChanges();
            Transport transport = session.getTransport("smtp");
            transport.connect(mailConfig.getHost(),mailConfig.getMailUser(), mailConfig.getMailPassword());
            transport.sendMessage(message,new Address[]{addressTo});
            transport.close();
        } catch (UnsupportedEncodingException | MessagingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送电子邮件
     * @param email 电子邮件地址
     * @param subject 电子邮件标题
     * @param text 电子邮件内容
     */
    public void sendEmail(String email, String subject, String text){
        sendEmail(email,subject,text,false);
    }


}
